package com.cn.ZhiKeDianShang.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.cn.ZhiKeDianShang.AppConfig;
import com.cn.ZhiKeDianShang.Oss.OssService;
import com.cn.ZhiKeDianShang.R;
import com.cn.ZhiKeDianShang.base.BaseActivity;
import com.cn.ZhiKeDianShang.model.response.RroandCityBean;
import com.cn.ZhiKeDianShang.model.response.UserInfoBean;
import com.cn.ZhiKeDianShang.presenter.LoginUserPresenter;
import com.cn.ZhiKeDianShang.presenter.view.LoginUserView;
import com.cn.ZhiKeDianShang.util.BitmapUtil;
import com.cn.ZhiKeDianShang.util.JsonUitl;
import com.cn.ZhiKeDianShang.util.Netdialog.StyledDialog;
import com.cn.ZhiKeDianShang.util.PrefShare;
import com.cn.ZhiKeDianShang.util.TimeSelect.CustomAdressPicker;
import com.cn.ZhiKeDianShang.util.ToastUtil;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.HttpUtils;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.callback.JsonCallback;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.ObjectResult;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.Result;
import com.makeramen.roundedimageview.RoundedImageView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.compress.FileUtil;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhihu.matisse.internal.ui.widget.CropImageView;
import com.zhihu.matisse.listener.OnSelectedListener;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/7/3.
 * do what to 2017/7/3
 */

public class UpdateInfoActivity extends BaseActivity<LoginUserView, LoginUserPresenter> implements LoginUserView {

    @BindView(R.id.setting_back)
    ImageView settingBack;
    @BindView(R.id.im_photo)
    RoundedImageView imPhoto;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_adress)
    TextView tvAdress;
    @BindView(R.id.tv_sex)
    TextView tv_sex;

    @Override
    protected int getNormalLayoutId() {
        return R.layout.activity_update_info;
    }

    @Override
    protected int getErrorLayoutId() {
        return R.layout.activity_update_info;
    }

    @Override
    protected LoginUserPresenter createPresenter() {
        return new LoginUserPresenter(this, this);
    }

    @Override
    protected void initViewsAndEvents() {
        String avatar = PrefShare.getInstance(this).getString("avatar");
        String nickname = PrefShare.getInstance(this).getString("nickname");
        String provincename = PrefShare.getInstance(this).getString("provincename");
        String cityname = PrefShare.getInstance(this).getString("cityname");
        String gender = PrefShare.getInstance(this).getString("gender");
        Glide.with(this)
                .load(avatar)
                .into(imPhoto);
        tvNickname.setText(nickname);
        tvAdress.setText(provincename + "-" + cityname);
        if (gender.equals("1")) {
            tv_sex.setText("男");
        } else if (gender.equals("2")) {
            tv_sex.setText("女");
        } else {
            tv_sex.setText("保密");
        }
    }


    /**
     * @param
     */
    private void getPro() {
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        HttpUtils.post().url(AppConfig.COMMON_PROVINCE)
                .params(params)
                .build()
                .execute(new JsonCallback() {

                    @Override
                    public void onResponse(String result) {
                        RroandCityBean bean = (RroandCityBean) JsonUitl.stringToObject(result, RroandCityBean.class);
                        AdressPicker(bean.getData());
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    CustomAdressPicker customAdressPicker;
    //弹框选择的地址
    String handleproName = "";
    String handlecityName = "";

    /**
     * 显示时间
     */
    private void AdressPicker(List<RroandCityBean.DataBean> data) {
        //获取当前时间
        //tvElectricalTime.setText(now.split(" ")[0]);
        customAdressPicker = new CustomAdressPicker(UpdateInfoActivity.this, data, new CustomAdressPicker.ResultHandler() {
            @Override
            public void handle(String proName, String proId, String cityName, String cityId) {
                Log.d("yyyyy", "返回的省的名字" + proName + "---" + proId + "----" + cityName + "----" + cityId);
                handleproName = proName;
                handlecityName = cityName;
                updateInfo(3, "", proId, cityId);
            }

        }); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customAdressPicker.setIsLoop(); // 设置控件循环滚动 （这个在方法里面设置 相应控件能不能循环滑动）
        customAdressPicker.show();
    }


    /**
     * //    1是修改头像  2是修改昵称   3 修改地址  4是修改性别
     * <p>
     * 头像 昵称  性别 三个取info参数     地址取province city参数
     */
    private void updateInfo(int type, String info, String province, String city) {
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        if (type == 1) {
            params.put("avatar", info);
        } else {
            params.put("avatar", PrefShare.getInstance(this).getString("avatar"));
        }

        if (type == 2) {
            params.put("nickname", info);
        } else {
            params.put("nickname", PrefShare.getInstance(this).getString("nickname"));
        }
        if (type == 3) {
            //这里暂时 传的是死数据  等选择框搞好了  用实时数据
            params.put("province", province);
            params.put("city", city);
        } else {
            params.put("province", PrefShare.getInstance(this).getString("province"));
            params.put("city", PrefShare.getInstance(this).getString("city"));
        }
        if (type == 4) {
            params.put("gender", info);
        } else {
            params.put("gender", PrefShare.getInstance(this).getString("gender"));
        }
        HttpUtils.post().url(AppConfig.USER_PROFILE)
                .params(params)
                .addSecret()
                .build()
                .execute(new BaseCallback<LoginRegisterResult>(LoginRegisterResult.class) {
                    @Override
                    public void onResponse(ObjectResult<LoginRegisterResult> result) {
                        Log.d("Debug", "到达请求这里---");
                        if (Result.checkSuccess(UpdateInfoActivity.this, result)) {
                            switch (type) {
                                case 1:
                                    ToastUtil.showShort("修改头像成功");
                                    Glide.with(UpdateInfoActivity.this)
                                            .load(info)
                                            .into(imPhoto);
                                    break;
                                case 2:
                                    ToastUtil.showShort("修改昵称成功");
                                    tvNickname.setText(info + "");
                                    break;
                                case 3:
                                    ToastUtil.showShort("修改地址成功");
                                    tvAdress.setText(handleproName + "-" + handlecityName);
                                    break;
                                case 4:
                                    ToastUtil.showShort("修改性别成功");
                                    if (info.equals("1")) {
                                        tv_sex.setText("男");
                                    } else if (info.equals("2")) {
                                        tv_sex.setText("女");
                                    } else {
                                        tv_sex.setText("保密");
                                    }
                                    PrefShare.getInstance(UpdateInfoActivity.this).saveString("gender", info + "");
                                    break;

                            }

                        }
                        StyledDialog.dismiss(gloablDialog);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                        StyledDialog.dismiss(gloablDialog);
                    }
                });
    }


    @Override
    public void onLogin(UserInfoBean resultBean) {

    }

    @Override
    public void requestFailed(String message) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    //上传的进度回调
    String accessKeyId = "LTAI4FpBbo7yfZx1waLnveHQ";
    String accessKeySecret = "aymEw4VmeHKuFtnyYVoyDIziQrCLff";
    String endpoint = "http://cdnzkds.zyfjsm.com";
    String bucketName = "gpos-zkds";
    Dialog gloablDialog;


    @OnClick({R.id.setting_back, R.id.ll_updateimage, R.id.rl_updatenickname, R.id.rl_updatenadress, R.id.rl_updatensex})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.setting_back:
                finish();
                break;
            case R.id.ll_updateimage:
                initPermission();
                break;
            case R.id.rl_updatenickname:
                Intent newIntent = new Intent(UpdateInfoActivity.this, ChangeUserNameActivity.class);
                newIntent.putExtra("username", tvNickname.getText().toString());
                // 开始一个新的 Activity等候返回结果
                startActivityForResult(newIntent, 1001);
                break;
            case R.id.rl_updatenadress:
                getPro();
                break;
            case R.id.rl_updatensex:
                Intent newIntent1 = new Intent(UpdateInfoActivity.this, ChangeSexNameActivity.class);
                newIntent1.putExtra("gender", PrefShare.getInstance(this).getString("gender"));
                // 开始一个新的 Activity等候返回结果
                startActivityForResult(newIntent1, 1002);
                break;
        }
    }


    private void initPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);

        rxPermissions.request(
                Manifest.permission.CAMERA
                , Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.READ_EXTERNAL_STORAGE
        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    //申请的权限全部允许
                    Matisse.from(UpdateInfoActivity.this)
                            .choose(MimeType.ofImage(), false)
                            .showSingleMediaType(true)
                            .countable(true)
                            .capture(true) //是否使用拍照
                            .isCrop(true)
                            .captureStrategy(
                                    new CaptureStrategy(true, "com.cn.ZhiKeDianShang"))
                            .maxSelectable(1)
                            .isCrop(true) //是否剪切
                            .cropStyle(CropImageView.Style.CIRCLE)
                            .isCropSaveRectangle(false)
                            .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                            .originalEnable(true)
                            .maxOriginalSize(10)
                            .thumbnailScale(0.85f)
                            .imageEngine(new GlideEngine())
                            .setOnSelectedListener(new OnSelectedListener() {
                                @Override
                                public void onSelected(@NonNull List<Uri> uriList, @NonNull List<String> pathList) {
                                    if (uriList != null && uriList.size() > 0 && pathList != null && pathList.size() > 0) {
                                        Log.d("Leo", uriList.size() + " " + uriList.get(0) + " " + pathList.size() + " " + pathList.get(0));
                                    }
                                }
                            })
                            .forResult(1000);
                } else {
                    //只要有一个权限被拒绝，就会执行
                    Toast.makeText(UpdateInfoActivity.this, "未授权权限，部分功能不能使用", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    public void uploadOssImage(OssService ossService, int position, int sumNumber, String loacalImageurl) {
//开始上传，参数分别为content，上传的文件名filename，上传的文件路径filePath
        ossService.beginupload(UpdateInfoActivity.this, position, sumNumber, createOssurl(), loacalImageurl, new OssService.OnUploadListener() {
            @Override
            public void onProgress(double progress) {

            }

            @Override
            public void onSuccess(int position, int sumNumber, String uploadPath, String imageUrl) {
                Log.d("Debug", "图片上传成功回调" + "上传地址" + uploadPath);
                Log.d("Debug", "图片上传成功回调" + "阿里云地址" + imageUrl);
                //上传头像
                updateInfo(1, imageUrl, "", "");
            }

            @Override
            public void onFailure(int position) {

            }
        });
    }

    /**
     * 创建oss上传地址
     *
     * @return
     */
    public String createOssurl() {
        String userid = PrefShare.getInstance(UpdateInfoActivity.this).getString("userId");
        String random = (int) ((Math.random() * 9 + 1) * 1000) + "";
        String url = "avatar/" + getTime() + "/" + userid + System.currentTimeMillis() + random + "ad";
        return url;
    }

    public String getTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date(System.currentTimeMillis());
        String time = sdf.format(date);
        return time;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("Debug", "到达回调这里");
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                case 1000:
                    try {
                        //没压缩之前的文件
                        List<String> originalPath = Matisse.obtainPathResult(data);
//                    //获得没压缩的文件
                        File file = FileUtil.getFileByPath(Matisse.obtainPathResult(data).get(0));
                        //下面是上传阿里云
                        long fileSize = getFileSize(file);
                        Log.d("Debug", "返回的图片数据大小" + fileSize / 1024 + "kb");
                        String url = "";
                        //图片大于大于200kb  压缩操作
                        if (fileSize / 1024 > 200) {
                            //获得压缩的文件
//                            File file1 = CompressHelper.getDefault(getApplicationContext()).compressToFile(file);
//                            url = file1.getPath();
                            url = BitmapUtil.compressImage(file.getPath());
                        } else {
                            url = file.getPath();
                        }
                        gloablDialog = StyledDialog.buildLoading(UpdateInfoActivity.this, "上传中...").show();
                        //初始化OssService类，参数分别是Content，accessKeyId，accessKeySecret，endpoint，bucketName（后4个参数是您自己阿里云Oss中参数）
                        OssService ossService = new OssService(UpdateInfoActivity.this, accessKeyId, accessKeySecret, endpoint, bucketName);
                        //初始化OSSClient
                        ossService.initOSSClient();
                        uploadOssImage(ossService, 1, 1, originalPath.get(0));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //上传图片操作
                    break;
                case 1001:
                    //修改昵称操作
                    String username = data.getStringExtra("username");
                    if (!TextUtils.isEmpty(username)) {
                        updateInfo(2, username, "", "");
                    }
                    break;
                case 1002:
                    //修改性别
                    String gender = data.getStringExtra("gender");
                    if (!TextUtils.isEmpty(gender)) {
                        updateInfo(4, gender, "", "");
                    }
                    break;

            }

        }
    }


    /**
     * 获取指定文件大小
     */
    public long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }


}
